package com.power.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: 朱雄
 * Date: 2020/09/22 17:27
 * Description:
 * Version: V1.0
 * @author
 */
public class UploadFile {
    /**
     *创建一个map集合用于存放表单数据
     *
     */
    public static Map<String,Object> formData=new HashMap<>();

    public static boolean uploadFile(HttpServletRequest req) throws FileUploadException, IOException {
        req.setCharacterEncoding("utf-8");
        DiskFileItemFactory diskFileItemFactory=new DiskFileItemFactory();
        ServletFileUpload servletFileUpload=new ServletFileUpload(diskFileItemFactory);
        servletFileUpload.setHeaderEncoding("UTF-8");
        //设置文件上传总大小
        servletFileUpload.setFileSizeMax(1024*1024*100);
        //设置单个文件大小
        servletFileUpload.setFileSizeMax(1024*1024*10);
        //将 request对象放置到上组件
        List<FileItem> fileItems= servletFileUpload.parseRequest(req);
        for (FileItem fileitem:fileItems) {
            if (fileitem.isFormField()){
                String fileName=fileitem.getFieldName();
                String fileValue=fileitem.getString();
                formData.put(fileName,fileValue);
            }else{
                InputStream in=fileitem.getInputStream();
                //获得文件名
                String sourceFileName=fileitem.getName();
                //获得项目根路径
                String contextPath=req.getServletContext().getRealPath("/");
                //上传文件存放路径
                Date date=new Date();
                int year=date.getYear()+1900;
                int month=date.getMonth()+1;
                File file=new File(contextPath+File.separator+"upload"+File.separator+year+File.separator+month+File.separator);
                if (!file.exists()){
                    file.mkdirs();
                }
                String ext=sourceFileName.substring(sourceFileName.lastIndexOf("."),sourceFileName.length());
                //文件上传限制
                String allowExt=".png|.jpg";
                if (allowExt.indexOf(ext)==-1){
                    throw new FileUploadException("不允许上传"+ext+"此类型文件");
                }
                String newFileName=UuidUtil.getUUID()+ext;
                //拼接路径，文件夹路径+文件名
                String uploadPath=file+File.separator+newFileName;
                System.out.println(uploadPath);
                //获得输出流
                OutputStream os=new FileOutputStream(uploadPath);
                //设置读取速度
                byte[] bytes=new byte[1024*1024];
                int len;
                while ((len=in.read(bytes))!=-1){
                    os.write(bytes,0,len);
                    os.flush();
                }
                os.close();
                os.close();
                String str= File.separator+"upload"+File.separator+year+File.separator+month+File.separator+newFileName;
                formData.put("formUrl",str.replace("\\","/"));
            }
        }
            return true;
    }
}
